/**
 *抽屉js 
 **/

/**
 * 添加数据
 **/
function saveDrawer(data){
	db.transaction(function (tx) {
    	tx.executeSql("INSERT INTO DRAWER (ID,NAME,SORT,STATUS,PID) VALUES (?,?,?,?,?)",
    			[data.id==undefined ? '' :data.id,data.text==undefined ? '' :data.text,
    			 data.sort==undefined ? '' :data.sort,data.status==undefined ? '' :data.status,
    			 data.pid==undefined ? '' :data.pid],
       function (tx, rs) {
       },
	   function (tx, error) {
    	   message("添加抽屉数据失败");
	   });
    });
}

/**
 * 通过PID获取抽屉
 * @param pid 父ID
 * @param callback 回调函数
 * @param $con 容器节点
 */
function findDrawerByPid(pid,callback,$con){
	db.transaction(function (tx) { 
		tx.executeSql("SELECT ID,NAME,SORT,STATUS,PID FROM DRAWER WHERE PID = ? ORDER BY SORT ASC", [pid], 
		function (tx, results){
			var data = new Array();
		    var len = results.rows.length; 
		    for (var i = 0; i < len; i++){ 
		    	var drawer = {};
		    	drawer.id = results.rows.item(i).ID;
		    	drawer.name = results.rows.item(i).NAME;
		    	drawer.pid = results.rows.item(i).PID;
		    	drawer.sort = results.rows.item(i).SORT;
		    	drawer.status = results.rows.item(i).STATUS;
		    	data.push(drawer);
		    }
			if (typeof(callback) == 'function'){
				callback(data,$con);
			}
	    }, 
	    function(tx, ex) {
	    	message("获取抽屉失败");
        });
	});
}

/**
 * 通过ID查询抽屉
 **/
function findDrawerById(id, callback,datarow){
	db.transaction(function (tx) {
		tx.executeSql('SELECT * FROM DRAWER WHERE ID = ?', [id], function (tx, results){
		    var len = results.rows.length;
		    if(len == 0 || len > 1){
		    	message("获取字典失败");
		    	return;
		    }
		    var data = {};
		    for (var i = 0; i < len; i++){ 
		    	data.id = results.rows.item(i).ID;
		    	data.name = results.rows.item(i).NAME;
		    	data.pid = results.rows.item(i).PID;
		    	data.sort = results.rows.item(i).SORT;
		    	data.status = results.rows.item(i).STATUS;
		    }
			if (typeof(callback) == 'function'){
				callback(data,datarow);
			}
	    }, 
	    function(tx, ex) {
	    	message("获取抽屉失败");
        });  
	});
}

/**
 * 初始化抽屉
 **/
function drawer(callback,data){
	db.transaction(function (tx) { 
		tx.executeSql('DELETE FROM DRAWER', [], 
		function (tx, results){
			if (typeof(callback) == 'function'){
				$.each(data,function(index,item){
					callback(item);
				});
			}
		}, 
		function (tx, ex){
			message("删除抽屉数据失败");
		});  
	});
}

/**
 * 初始化抽屉数据
 * @param db
 * @param callback
 **/
function initDrawer(){
	drawer(getDrawerData);
}

//=============

/**
 * 从服务器上获取抽屉所有数据.
 **/
function getDrawerData(){
	$.ajax({
		type : "post",
		url : getContextPath() + "/drawer/findAll",
		dataType : "json",
		error : function(request) {
			message("获取抽屉列表数据失败");
		},
		success : function(data) {
			$.each(data, function(i, item) {
				/**
				 * 添加到本地
				 **/
				saveDrawer(item);
			});
			message("获取抽屉列表数据成功");
		}
	});
}